package com.filetransfer.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@SpringBootApplication

//外层url
@RequestMapping("fileServer")
@RestController
public class Server {
    //根据配置文件自动注入
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Server.class, args);
    }

    /**
     * 上传接口 ../fileServer/upload  POST
     * 通过http协议对传输文件进行存储记录
     * @param request   请求对象
     * @return  String  返回uuid
     * @throws IOException  读写异常处理
     * @throws ServletException 网络异常处理
     */
    @RequestMapping("upload")
    public String upload(HttpServletRequest request) throws IOException, ServletException {
        //通过键值提取请求中的信息
        String fileName = request.getHeader("fileName");
        String fileType = request.getHeader("fileType");
        String fileSize = request.getHeader("fileSize");
        byte[] bytes = request.getInputStream().readAllBytes();

        //日期格式转换对象及日期对象
        SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        //生成uuid
        String uuid = UUID.randomUUID().toString();
        //存储文件目录及路径
        String dirName = formatter.format(date);
        formatter.applyPattern("hh:mm:ss");
        String storeTime = formatter.format(date);
        String dir = "/Users/eric/code/test";
        String fileDir = dir+"/"+dirName;

        //文件夹创建及文件写入
        File file = new File(fileDir);
        if(!file.isDirectory()){
            file.mkdir();
            writeFile(fileDir+"/"+uuid,bytes);
        }else {
            writeFile(fileDir+"/"+uuid,bytes);
        }

        //元数据写入数据库
        String sql = "insert into fileServer(uuid,fileName,fileType,fileSize,fileDir,storeTime) values ('"+uuid+"','"+fileName+"','"+fileType+"','"+fileSize+"','"+fileDir+"','"+storeTime+"');";
        jdbcTemplate.execute(sql);
        return uuid;

        //开始用postman的form-data模拟请求，写客户端时，发现用纯Java写太麻烦，改用IO流来上传/下载


//        Part part = request.getPart("file");
//        //日期格式转换对象及日期对象
//        SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
//        Date date = new Date();
//
//        //生成uuid
//        String uuid = UUID.randomUUID().toString();
//        //从提取文件部分中提取相应信息
//        String fileName = part.getSubmittedFileName();
//        String fileType = part.getContentType();
//        long fileSize = part.getSize();
//        //存储文件目录及路径
//        String dirName = formatter.format(date);
//        formatter.applyPattern("hh:mm:ss");
//        String storeTime = formatter.format(date);
//        String dir = "/Users/eric/code/test";
//        String fileDir = dir+"/"+dirName;

//        //用输入流对象读取文本
//        InputStream inputStream = part.getInputStream();
//        byte[] bytes = inputStream.readAllBytes();
    }

    /**
     * 创建文件，进行文本写入
     * @param dir String 文件路径
     * @param text byte[] 文本内容
     * @throws IOException
     */
    public static void writeFile(String dir, byte[] text) throws IOException {
        FileOutputStream fileOutputStream;
        BufferedOutputStream bufferedOutputStream;
        fileOutputStream = new FileOutputStream(dir);
        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        bufferedOutputStream.write(text,0,text.length);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }


    /**
     * 下载接口，根据uuid，从数据库查询路径，读取文本流
     * @param request http请求对象
     * @return byte 文本流
     * @throws IOException
     */
    @RequestMapping("download")
    public byte[] download(HttpServletRequest request) throws IOException {
        String uuid = request.getHeader("uuid");
        String sql = "select fileDir from fileServer where uuid='"+uuid+"';";
        Map<String , Object> map = jdbcTemplate.queryForMap(sql);
        String dir = map.get("fileDir").toString()+"/"+uuid;

        FileInputStream fileInputStream = new FileInputStream(dir);
        byte[] bytes = fileInputStream.readAllBytes();
        return bytes;
    }

    /**
     * 获取文件元数据接口
     * @param request 请求体，含参 uuid
     * @return Map 返回Map形式的结果集
     */
    @RequestMapping("getInfo")
    public byte[] getInfo(HttpServletRequest request){
        String uuid = request.getHeader("uuid");
        String sql = "select * from fileServer where uuid='"+uuid+"';";
        Map<String , Object> map = jdbcTemplate.queryForMap(sql);

        String str = map.toString();
        return str.getBytes();
    }

}
